﻿using Mengsk.ProxyDelivery.Domain;
using Mengsk.ProxyDelivery.Service;
using Mengsk.ProxyDelivery.Service.Spider;
using Mengsk.ProxyDelivery.Service.Spider.Go2;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Mengsk.ProxyDelivery.GoodsSpider.UI
{
    /// <summary>
    /// Interaction logic for GoodsSpiderUC.xaml
    /// </summary>
    public partial class GoodsSpiderUC : UserControl
    {
        public string Title
        {
            get { return "厂家商品抓取"; }
        }

        public Control UIControl
        {
            get { return this; }
        }

        public GoodsSpiderUC()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (this.cbbSpiders.ItemsSource == null)
            {
                this.cbbSpiders.ItemsSource = new SpiderBase[]
                {
                    new Go2Spider(),
                };
            }
            this.cbbSpiders.SelectedIndex = 0;
        }

        private void btnSpiderVendor_Click(object sender, RoutedEventArgs e)
        {
            GoodsSpiderOneUC uc = this.dgSpiders.Children[0] as GoodsSpiderOneUC;
            uc.StartSycVendors(((this.cbbSpiders.SelectedItem as ICloneable).Clone() as SpiderBase), ServiceContainer.GetService<VendorService>()).ContinueWith(new Action<Task>(completedTask => this.Dispatcher.BeginInvoke(new Action(() => MessageBox.Show("已完成")))));
        }

        private void btnSpiderGoods_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                List<SpiderBase> spiders = new List<SpiderBase>();
                int count = int.Parse((this.cbbThreadCount.SelectedItem as ComboBoxItem).Content.ToString());
                for (int i = 0; i < count; i++)
                {
                    spiders.Add(((this.cbbSpiders.SelectedItem as ICloneable).Clone() as SpiderBase));
                }
                Vendor[] vendors = ServiceContainer.GetService<VendorService>().GetBySpider((int)spiders[0].SpiderType).ToArray();
                int eachCount = (vendors.Length + count - 1) / count;
                Vendor[][] arrayVendors = new Vendor[count][];
                for (int i = 0; i < arrayVendors.Length; i++)
                {
                    int len = vendors.Length - eachCount * i > eachCount ? eachCount : vendors.Length - eachCount * i;
                    Vendor[] tmp = new Vendor[len];
                    Array.Copy(vendors, eachCount * i, tmp, 0, len);
                    arrayVendors[i] = tmp;
                }
                GoodsSpiderOneUC[] uc = this.dgSpiders.Children.OfType<GoodsSpiderOneUC>().ToArray();

                for (int i = 0; i < count; i++)
                {
                    uc[i].StartSycGoodss(spiders[i], arrayVendors[i], ServiceContainer.GetService<ShoesService>());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnStopSpider_Click(object sender, RoutedEventArgs e)
        {
            foreach (GoodsSpiderOneUC uc in this.dgSpiders.Children)
            {
                uc.Stop();
            }
        }

        private void btnManual_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Vendor[] vendors = ServiceContainer.GetService<VendorService>().GetByName(this.tbManualVendor.Text.Trim()).ToArray();
                if (vendors.Length == 0)
                {
                    throw new Exception("未找到指定厂家");
                }
                SpiderBase spi = (this.cbbSpiders.SelectedItem as ICloneable).Clone() as SpiderBase;
                GoodsSpiderOneUC[] uc = this.dgSpiders.Children.OfType<GoodsSpiderOneUC>().ToArray();
                uc[0].StartSycGoodss(spi, vendors, ServiceContainer.GetService<ShoesService>());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void cbbThreadCount_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.dgSpiders.Children.Clear();
            this.dgSpiders.RowDefinitions.Clear();
            this.dgSpiders.ColumnDefinitions.Clear();
            ComboBoxItem item = this.cbbThreadCount.SelectedItem as ComboBoxItem;
            if (item == null)
            {
                return;
            }
            int count = int.Parse(item.Content.ToString());
            int rowCount = (int)(Math.Sqrt(count));

            for (int i = 0; i < rowCount; i++)
            {
                this.dgSpiders.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
                this.dgSpiders.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
            }

            //创建控件

            for (int i = 0; i < count; i++)
            {
                GoodsSpiderOneUC uc = new GoodsSpiderOneUC { ThreadNumber = "线程:" + (i + 1), Margin = new Thickness(4), BorderThickness = new Thickness(3), BorderBrush = Brushes.LightBlue, Name = "Thread" + (i + 1) };
                uc.SetValue(Grid.RowProperty, i / rowCount);
                uc.SetValue(Grid.ColumnProperty, i % rowCount);
                this.dgSpiders.Children.Add(uc);
            }
        }
    }
}
